<template>
  <el-dialog :visible.sync="dialogVisible" width="30%" :before-close="beforeClose" :title="dialogTitle">
    <el-form>
      <el-row class="row">
        <el-col :span="4">
          <span>所在部门</span>
        </el-col>
        <el-col :span="20">
          <el-select v-model="formData.whjg" filterable
                     placeholder="请选择部门">
            <el-option :label="option.deptName" :value="option.deptCode" v-for="(option, oi) in framedepartmentList"
                       :key="oi"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col :span="4">
          <span>区域代码</span>
        </el-col>
        <el-col :span="20">
          <dict-select v-model="formData.qydm" showCode :dict-code="DictCode.VMS_QYDM"
                       @change="changeQydm"></dict-select>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col :span="4">
          版式文件生成
        </el-col>
        <el-col :span="20">
          <el-select v-model="formData.bswjsczt">
            <el-option value="Y" label="启用">启用</el-option>
            <el-option value="N" label="关闭">关闭</el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col :span="4">
          发票开具
        </el-col>
        <el-col :span="20">
          <el-select v-model="formData.fpkjzt">
            <el-option value="Y" label="启用">启用</el-option>
            <el-option value="N" label="关闭">关闭</el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col :span="4">
          <span>使用单位编号</span>
        </el-col>
        <el-col :span="20">
          <el-input v-model="formData.sydwbh"></el-input>
        </el-col>
      </el-row>
      <el-row class="row">
        <el-col :span="4">
          版式文件
        </el-col>
        <el-col :span="20">
          <el-upload
              class="upload-component"
              ref="upload"
              :auto-upload="false"
              :file-list="fileList"
              :on-change="onChange"
              :on-remove="onRemove"
              :limit="1"
              action=""
              multiple
              drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text" v-if="formData.bswjid">上传图片覆盖原有印章图片</div>
            <div class="el-upload__text" v-else>请上传 PNG文件</div>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-col>
      </el-row>
    </el-form>
    <el-row style="margin-top: 10px">
      <div class="centered-dialog">
        <el-button type="primary" size="mini" @click="confirmSubmit" :loading="loading">
          {{ this.loading ? '正在上传， 请不要关闭' : '提交信息' }}
        </el-button>
        <el-button type="danger" size="mini" @click="clearFile">清空文件</el-button>
      </div>
    </el-row>
  </el-dialog>
</template>

<script>
import DictSelect from "@/views/invoiceTemplate/components/DictSelect/DictSelect.vue";
import {DictCode} from "@/utils/DictConstant";
import {getDetail, getFramedepartment, uploadAction} from "@/api/invoiceTemplate";

export default {
  computed: {
    DictCode() {
      return DictCode
    }
  },
  components: {DictSelect},
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    dialogTitle: {
      type: String,
      default: '上传版式文件'
    }
  },
  data() {
    return {
      dialogVisible: false,
      data: {},
      fileList: [],
      loading: false,
      formData: {
        whjg: "",
        qydm: "",
        qymc: "",
        sydwbh: "",
        bswjsczt: "",
        fpkjzt: "",
        bswjid: ""
      },
      framedepartmentList: [],
      row: {}
    };
  },
  mounted() {
    this.getFramedepartment();
  },
  methods: {
    async getDetail() {
      const {data, msg, code} = await getDetail(this.row.bswjid);
      if (code == 200) {
        this.formData = data;
      } else {
        this.$message.error("未查询到数据");
      }
    },
    beforeClose(done) {
      this.formData = {
        whjg: "",
        qydm: "",
        qymc: "",
        sydwbh: "",
        bswjsczt: "",
        fpkjzt: "",
        bswjid: ""
      }
      this.clearFile()
      this.$emit('update:dialogVisible', false);
      done();
    },
    onChange(file, fileList) {
      if (fileList.length > 1) {
        this.$message.error(`只能上传一个版式文件！`)
        return
      }

      let validSuffix = ['png']
      let splits = file.name.split('.')
      let suffix = splits[splits.length - 1]

      if (!validSuffix.includes(suffix)) {
        this.$message.error(`只能上传 ${validSuffix.join(',')} 类型的文件！`)
        this.fileList = fileList.filter(item => item.uid !== file.uid)
        return
      }
      this.fileList = fileList
    },

    onRemove(file, fileList) {
      this.fileList = fileList.filter(item => item.uid !== file.uid)
    },

    clearFile() {
      this.fileList = []
    },

    async confirmSubmit() {
      //判断是否有文件再上传
      if (this.fileList.length === 0 && this.formData.bswjid === "") {
        return this.$message.warning('请选取文件后再上传')
      }
      if (!this.formData.whjg) {
        return this.$message.warning('请选择所在部门')
      }
      if (!this.formData.qydm) {
        return this.$message.warning('请选择区域代码')
      }
      if (!this.formData.sydwbh) {
        return this.$message.warning('请输入使用单位编号')
      }
      if (!this.formData.bswjsczt) {
        return this.$message.warning('请选择版式文件生成状态')
      }
      if (!this.formData.fpkjzt) {
        return this.$message.warning('请选择发票开具状态')
      }

      // 创建 formData 对象
      const formData = new FormData()
      this.fileList.forEach((file) => {
        formData.append('file', file.raw)
      })
      formData.append('whjg', this.formData.whjg)
      formData.append('qydm', this.formData.qydm)
      formData.append('qymc', this.formData.qymc)
      formData.append('sydwbh', this.formData.sydwbh)
      formData.append('bswjsczt', this.formData.bswjsczt)
      formData.append('fpkjzt', this.formData.fpkjzt)
      formData.append('bswjId', this.formData.bswjid)
      this.loading = true
      let {data, code, message} = await uploadAction(formData)
      if (code == 200) {
        this.$parent.getList();
        this.clearFile();
        this.formData = {
          whjg: "",
          qydm: "",
          qymc: "",
          sydwbh: "",
          bswjsczt: "",
          fpkjzt: ""
        }
        this.loading = false
        this.beforeClose();
      }
      this.loading = false
    },
    async getFramedepartment() {
      let {data, code, message} = await getFramedepartment({});
      if (code == 200) {
        this.framedepartmentList = data
      } else {
        this.$message({
          type: 'success',
          message: message,
        })
      }
    },
    changeQydm(value, label) {
      this.formData.qymc = label;
    }
  },
};
</script>

<style scoped>
.centered-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}

.row {
  margin-bottom: 10px;
}
</style>